package org.wanho.txy.ems.controller;

import com.alibaba.fastjson.JSON;
import org.wanho.factory.ObjectFactory;
import org.wanho.txy.ems.constant.PaginationConstant;
import org.wanho.txy.ems.entity.User;
import org.wanho.txy.ems.param.UserParam;
import org.wanho.txy.ems.service.UserService;
import org.wanho.txy.ems.util.StringUtil;
import org.wanho.txy.ems.vo.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2023-05-10 15:36
 * Description：<描述>
 */
@WebServlet("*.user")
public class UserController extends HttpServlet {

    private UserService userService = (UserService) ObjectFactory.getObject("userServiceProxy");

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        if("/login.user".equals(path)){
            login(req,resp);
        }else if("/register.user".equals(path)){
            register(req,resp);
        }else if("/toAdd.user".equals(path)){
            req.getRequestDispatcher("/WEB-INF/pages/adduser.jsp").forward(req,resp);
        }else if("/toList.user".equals(path)){
            req.getRequestDispatcher("/WEB-INF/pages/listuser.jsp").forward(req,resp);
        }else if("/findByCondition.user".equals(path)){
            findByCondition(req,resp);
        }else if("/modifyStatus.user".equals(path)){
            modifyStatus(req,resp);
        }else if("/removeById.user".equals(path)){
            removeById(req,resp);
        }else if("/findById.user".equals(path)){
            findById(req,resp);
        }else if("/modify.user".equals(path)){
            modify(req,resp);
        }else if("/add.user".equals(path)){
            add(req,resp);
        }else if("/count.user".equals(path)){
            count(req,resp);
        }
    }

    private void count(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();
        try {
            int count = userService.selectCount(new UserParam());
            out.print(JSON.toJSONString(ResponseResult.success(count)));
        } catch (Exception e) {
            out.print(JSON.toJSONString(ResponseResult.fail(e.getMessage())));
        }
        out.close();
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        int age = Integer.parseInt(req.getParameter("age"));
        String avatar = req.getParameter("avatar");
        User user = new User(username, password, name, age, avatar);

        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();
        try {
            userService.add(user);
            out.print(JSON.toJSONString(ResponseResult.success()));
        } catch (Exception e) {
            out.print(JSON.toJSONString(ResponseResult.fail(e.getMessage())));
        }
        out.close();
    }

    private void modify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        int age = Integer.parseInt(req.getParameter("age"));
        User user = new User(id, username, password, name, age);

        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();
        try {
            userService.modify(user);
            out.print(JSON.toJSONString(ResponseResult.success()));
        } catch (Exception e) {
            out.print(JSON.toJSONString(ResponseResult.fail(e.getMessage())));
        }
        out.close();
    }

    private void findById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        User user = userService.findById(id);

        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();
        out.print(JSON.toJSONString(ResponseResult.success(user)));
        out.close();
    }

    private void removeById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        userService.removeById(id);

        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();
        out.print(JSON.toJSONString(ResponseResult.success()));
        out.close();
    }

    private void modifyStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        int status = Integer.parseInt(req.getParameter("status"));
        userService.modifyStatus(id,status);

        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();
        out.print(JSON.toJSONString(ResponseResult.success()));
        out.close();
    }

    private void findByCondition(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            String username = req.getParameter("username");
            String name = req.getParameter("name");
            String s1 = req.getParameter("status");
            int status = StringUtil.isEmpty(s1) ? -1 : Integer.parseInt(s1);
            String s2 = req.getParameter("page");
            int pageNo = StringUtil.isEmpty(s2) ? PaginationConstant.pageNo : Integer.parseInt(s2);
            String s3 = req.getParameter("limit");
            int pageSize = StringUtil.isEmpty(s3) ? PaginationConstant.pageSize : Integer.parseInt(s3);

            UserParam userParam = new UserParam(username, name, status);
            List<User> users = userService.findByCondition(userParam,pageNo,pageSize);
            int count = userService.selectCount(userParam);

            resp.setContentType("application/json;charset=utf8");
            PrintWriter out = resp.getWriter();
            out.print(JSON.toJSONString(ResponseResult.success(users,count)));
            out.close();
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        try {
            User user = userService.login(username, password);
            req.getSession().setAttribute("user",user);
            req.getRequestDispatcher("/WEB-INF/pages/main.jsp").forward(req,resp);
        } catch (Exception e) {
            req.setAttribute("errorMsg","登录失败，用户名或密码不正确！");
            req.getRequestDispatcher("/index.jsp").forward(req,resp);
        }
    }

    private void register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        int age = Integer.parseInt(req.getParameter("age"));
        User user = new User(username, password, name, age);

        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();
        try {
            userService.register(user);
            out.print(JSON.toJSONString(ResponseResult.success()));
        } catch (Exception e) {
            out.print(JSON.toJSONString(ResponseResult.fail(e.getMessage())));
        }
        out.close();
    }
}
